import { defineStore } from 'pinia';
import { RouteRecordRaw } from 'vue-router';

import { getMenuList } from '@/api/permission';
import router, { fixedRouterList, homepageRouterList } from '@/router';
import { store } from '@/store';
// import { transformObjectToRoute } from '@/utils/route'; 将背景对象变成路由对象

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    whiteListRouters: ['/login'],
    routers: [],
    removeRoutes: [],
    asyncRoutes: [],
    buttons: [] as any[],
    isExpand: true,
  }),
  actions: {
    toggleExpand() {
      this.isExpand = !this.isExpand;
    },
    async initRoutes() {
      const accessedRouters = this.asyncRoutes;

      const processMenuItems = (items: any) => {
        items.forEach((item: any) => {
          if (item.children && item.children.length > 0) {
            // 递归处理子项
            processMenuItems(item.children);
            // 过滤出按钮数据并添加到 buttons 数组
            const buttons: any[] = item.children.filter((child: any) => child.menuType === 'operate');
            if (buttons.length > 0) {
              this.buttons.push(...buttons);
            }
            // 删除按钮数据
            item.children = item.children.filter((child: any) => child.menuType !== 'operate');
            // 如果 children 为空，删除 children 属性
            if (item.children.length === 0) {
              delete item.children;
            }
          } else {
            delete item.children;
          }
        });
      };
      // 调用函数处理数据
      console.log('组装路由前', accessedRouters);
      processMenuItems(accessedRouters);

      console.log('组装路由后', accessedRouters);
      this.routers = accessedRouters;
      // 在菜单展示全部路由
      // this.routers = [...homepageRouterList, ...accessedRouters, ...fixedRouterList] as any;
      // 在菜单只展示动态路由和首页
      // this.routers = [...homepageRouterList, ...accessedRouters];
      // 在菜单只展示动态路由
      // this.routers = [...accessedRouters];
    },
    async buildAsyncRoutes() {
      try {
        // 发起菜单权限请求 获取菜单列表
        const data: any = await getMenuList();
        const asyncRoutes: Array<RouteRecordRaw> = data;
        // this.asyncRoutes = transformObjectToRoute(asyncRoutes);
        this.asyncRoutes = asyncRoutes as any;
        await this.initRoutes();
        return this.asyncRoutes;
      } catch (error) {
        throw new Error("Can't build routes");
      }
    },

    async restoreRoutes() {
      // 不需要在此额外调用initRoutes更新侧边导肮内容，在登录后asyncRoutes为空会调用
      this.asyncRoutes.forEach((item: RouteRecordRaw) => {
        if (item.name) {
          router.removeRoute(item.name);
        }
      });
      this.asyncRoutes = [];
    },
  },
  persist: true,
});

export function getPermissionStore() {
  return usePermissionStore(store);
}
